<?php

namespace app\business\controller;

use app\models\{Shoplist};
use think\Db;
use think\Validate;

class Index extends Base
{
    public function login()
    {
        $admin_id = session('business_id');
        if (Shoplist::get($admin_id)) {
            return redirect('/main/index');
        }
        $data = $this->request->post();
        if ($this->request->isPost()) {
            $validate = new Validate([
                'username' => 'require',
                'password' => 'require',
                'code' => 'require',
            ], [
                'username.require' => '登录账号不能为空',
                'password.require' => '登录密码不能为空',
                'code.require' => '验证码不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            if (!captcha_check($data['code'])) {
                return json(['code' => 1, 'msg' => '验证码错误']);
            }
            $business = (new Shoplist())->where(['account' => $data['username']])->find();
            if (empty($business)) {
                return json(['code' => 1, 'msg' => '账号或密码错误1']);
            }
            if ($business['password'] != md5(md5($data['password']))) {
                return json(['code' => 1, 'msg' => '账号或密码错误2']);
            }
            session('business_id', $business['id']);
            return json(['code' => 0, 'msg' => '登陆成功', 'url' => url('main/index')]);
        }

        return view(null, [
            'data' => $data
        ]);
    }

    public function logout()
    {
        session('business_id', null);
        $this->redirect('index/login');
    }
}
